import axios from "axios";
import { getToken } from "./auth";
// import { ApiResponse } from "../api/common";

export const request = axios.create({
  baseURL: process.env.NEXT_PUBLIC_BASE_URL,
});

request.interceptors.request.use((config) => {
  config.headers["clientId"] = process.env.NEXT_PUBLIC_CLIENT_ID;
  config.headers["Content-Type"] = "application/json";
  if (getToken()) {
    config.headers["Authorization"] = `Bearer ${getToken()}`;
  }

  // 做个分页适配
  if (config.params) {
    config.params.pageNum = config.params.current;
    delete config.params.current;
  }

  return config;
});

request.interceptors.response.use((res) => {
  const data = res.data;

  if (
    res.request.responseType === "blob" ||
    res.request.responseType === "arraybuffer"
  ) {
    return res.data;
  }

  if (data.code === 401) {
    window.location.href = "/login";
  }

  // 500 错误
  if (data.code !== 200) {
    return new Promise((resolve, reject) => {
      reject(res.data);
    });
  }

  return res.data;
});

export default request;
